package com.rytong.tools.ui;

import java.util.Calendar;
import com.rytong.tools.utils.Utils;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.TextView;

public class LPElevator extends Component {
    private String linkedUrl_;

    int leftBtBgX_;
    int leftRightBtBgY_;
    int rightBtBgX_;

    protected CssStyle cssStyle_;

    int field_;// 域下标：1：左箭头；2：数字日期域；3：右箭头
    int backH_;// 背景高
    int state_;// 控件状态：1：普通；2：焦点；3：按下

    // 日期域背景
    Bitmap etNormalBack_;
    Bitmap etFocusBack_;

    // 左箭头
    Bitmap leftArrowNormal_;
    Bitmap leftArrowFocus_;
    // 右箭头
    Bitmap rightArrowNormal_;
    Bitmap rightArrowFocus_;

    public class MyLPElevator extends TextView implements CompositedComponent {

        public MyLPElevator(Activity activity, String value) {
            // TODO Auto-generated constructor stub
            super(activity);
            // 设置可获取焦点
            setFocusable(true);
            // 设置可触摸获取焦点
            setFocusableInTouchMode(true);
            setText(value);
        }

        @Override
        public Component composited() {
            // TODO Auto-generated method stub
            return LPElevator.this;
        }

        protected void onDraw(Canvas g) {
            if (!isFocused()) {
                state_ = 1;
            }
            if (isFocused() && state_ == 1) {
                state_ = 2;
            }
            switch (field_) {
            case 1:// 画左箭头

                break;
            case 2:// 画日期域
                switch (state_) {
                case 1:// normal
                    g.drawBitmap(etNormalBack_, 5, 0, paint_);
                    break;
                case 2:// focus
                    g.drawBitmap(etFocusBack_, 5, 0, paint_);
                    break;
                case 3:// down
                    break;
                }
                g.drawText((String) getText(), 10, (backH_ + paint_.getTextSize() - 4) / 2, paint_);
                break;
            case 3:// 画右箭头
                break;
            }
            drawBorder(g);
        }

        /**
         * 觸摸響應
         * */
        public boolean onTouchEvent(MotionEvent me) {
            int touchEvent = me.getAction();
            boolean isAction = false;
            switch (touchEvent) {
            case MotionEvent.ACTION_DOWN:
                requestFocus();
                state_ = 3;
                isAction = true;
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                invalidate();
                switch (field_) {
                case 1:// left
                    resetDate(-1);
                    break;
                case 2:// date
                    break;
                case 3:// right
                    resetDate(1);
                    break;
                }
                break;
            default:
                isAction = super.onTouchEvent(me);
            }
            return isAction;
        }

        /**
         * 响应按键按下操作
         * */
        public boolean onKeyDown(int keyCode, KeyEvent event) {

            if (!isFocused())
                return super.onKeyDown(keyCode, event);

            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                state_ = 3;
                break;
            default:
                return super.onKeyDown(keyCode, event);
            }
            invalidate();
            return true;
        }

        /**
         * 响应按键弹起操作
         * */
        public boolean onKeyUp(int keyCode, KeyEvent event) {

            if (!isFocused())
                return super.onKeyDown(keyCode, event);

            switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_CENTER:
                state_ = 2;
                switch (field_) {
                case 1:
                    resetDate(-1);
                    break;
                case 2:
                    break;
                case 3:
                    resetDate(1);
                    break;
                }
                break;
            default:
                return super.onKeyDown(keyCode, event);
            }
            invalidate();
            return true;
        }
    }

    /**
     * 重設日期
     * 
     * @param n
     *            int
     * */
    public void resetDate(int n) {
        int index = 0;
        try {
            String value = getContentText();
            int year = Integer.parseInt(value.substring(index, value.indexOf('-')));
            index = value.indexOf('-') + 1;
            int month = Integer.parseInt(value.substring(index, value.indexOf('-', index)));
            index = value.indexOf('-', index) + 1;
            int date = Integer.parseInt(value.substring(index));

            date += n;
            if (date < 1) {
                month--;
                if (month < 1) {
                    year--;
                    month = 12;
                    date = 31;
                } else {
                    date = getDayCount(year, month);
                }
            } else if (date > getDayCount(year, month)) {
                date = 1;
                month++;
                if (month > 12) {
                    year++;
                    month = 1;
                }
            }
            dealUserSelectDate(year, month, date);

        } catch (NumberFormatException e) {
            Utils.printOutToConsole("parseInt fail!!!" + e);
        }
    }

    /**
     * 用户选择日期后的逻辑处理
     * */
    public void dealUserSelectDate(int year, int month, int date) {
        StringBuffer newDateString = new StringBuffer();
        newDateString.append(year);
        newDateString.append('-');
        if (month < 10)
            newDateString.append('0');
        newDateString.append(month);
        newDateString.append('-');
        if (date < 10)
            newDateString.append('0');
        newDateString.append(date);
        // 重置日期
        String value = newDateString.toString();
        property_.put("text", value);
        if (isNotOverPastDate(year, month, date)) {
            setText(value);
            if (realView_ != null) {
                realView_.invalidate();
            }
        }
        pointerPressed((Activity) realView_.getContext());
    }

    private void setText(String value) {
        // TODO Auto-generated method stub
        MyLPElevator temp = (MyLPElevator) realView_;
        temp.setText(value);
    }

    /**
     * 比较用户选择的日期是否已经过去
     * 
     * @return true：未过去；false：已过去
     * */
    private boolean isNotOverPastDate(int year, int month, int date) {
        Calendar c = Calendar.getInstance();
        int currentYear = c.get(Calendar.YEAR);
        int currentMonth = c.get(Calendar.MONTH) + 1;
        int currentDay = c.get(Calendar.DAY_OF_MONTH);

        if (year > currentYear)
            return true;
        if (month > currentMonth)
            return true;
        if (date >= currentDay)
            return true;

        return false;
    }

    /**
     * 獲取某年某月的天數，傳入非法月份時返回零
     * 
     * @param year
     *            int 某年
     * @param month
     *            int 某月
     * */
    private int getDayCount(int year, int month) {
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            return 31;
        case 4:
        case 6:
        case 9:
        case 11:
            return 30;
        case 2:
            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {// ��?
                return 29;
            } else {
                return 28;
            }
        default:
            return 0;
        }
    }

    // 响应点击该按钮的执行操作
    void pointerPressed(Activity bv) {
        try {
            listener_.componentAction(this);
        } catch (Exception ex) {
            Utils.printException(ex);
        }
    }

    /**
     * 更新样式赋值，由于在lua中会有更新样式的操作，但是不涉及控件大小的改变，所以将此部分单独出来。
     */
    public void mouldCssStyle() {
        // TODO Auto-generated method stub
        super.mouldCssStyle();
        MyLPElevator mlpl = (MyLPElevator) realView_;
        Paint paint = mlpl.getPaint();
        // 设置字体或者绘制效果平滑
        paint.setAntiAlias(true);

        // 设置字体大小
        String temp = (String) cssStyle_.getProperty(CssStyle.FONTSIZE);
        if (!temp.equals("")) {
            int fontSize = Integer.parseInt(temp);
            fontSize = Utils.getFontSize(fontSize);
            if (fontSize > 0) {
                mlpl.setTextSize(fontSize);
            }
        }
        // 设置字体颜色
        mlpl.setTextColor(fgColor());
        // 设置字体权重
        temp = null;
        temp = (String) cssStyle_.getProperty(CssStyle.FONTWEIGHT);
        if (null != temp && !temp.equals("")) {
            setTypeFace((TextPaint) paint, temp);
        }
    }

    @Override
    public void mouldH() throws Exception {
        super.mouldH();
        init();
    }

    /*
     * ************************************************************************
     * Set and Get methods. ************************************************************************
     */
    /**
     * @param linkedUri
     *            the linkUrl_ to set
     */
    public void setLinkedUri(String linkedUri) {
        linkedUrl_ = linkedUri;
    }

    /**
     * @return the linkUrl_
     */
    public String linkedUri() {
        return linkedUrl_;
    }

    @Override
    public void initRealView(Activity activity, String value) {
        // TODO Auto-generated method stub
        realView_ = new MyLPElevator(activity, value);
    }

    /**
     * 初始化数据
     * */
    private void init() {
        paint_ = ((MyLPElevator) realView_).getPaint();
        int dateBackW = (int) paint_.measureText("0000-00-00") + 10;
        int arrowBackW = 30;
        int arrowW = 0;
        int arrowH = 0;
        // 初始化控件状态
        state_ = 1;

        Bitmap buttonAllImg = ImageRepository.getImageFromAssetFile(realView_.getContext(), "elevatorallback.png");
        if (buttonAllImg != null) {
            int baiW = buttonAllImg.getWidth();
            int baiH = buttonAllImg.getHeight();
            Bitmap normalBack = Bitmap.createBitmap(buttonAllImg, 0, 0, baiW / 3, baiH);
            Bitmap focusBack = Bitmap.createBitmap(buttonAllImg, baiW / 3, 0, baiW / 3, baiH);
            Bitmap downBack = Bitmap.createBitmap(buttonAllImg, baiW * 2 / 3, 0, baiW / 3, baiH);

            try {
                etNormalBack_ = LPButton.makeButton(normalBack, dateBackW);
                etFocusBack_ = LPButton.makeButton(focusBack, dateBackW);
            } catch (Exception e) {
                Utils.printException(e);
            }
            if (!buttonAllImg.isRecycled()) {
                buttonAllImg.recycle();
            }
            buttonAllImg = null;
            if (normalBack != null && !normalBack.isRecycled()) {
                normalBack.recycle();
            }
            normalBack = null;
            if (focusBack != null && !focusBack.isRecycled()) {
                focusBack.recycle();
            }
            focusBack = null;
            if (downBack != null && !downBack.isRecycled()) {
                downBack.recycle();
            }
            downBack = null;
        }

        rightArrowNormal_ = ImageRepository.getImageFromAssetFile(realView_.getContext(), "arrownormal.png");
        rightArrowFocus_ = ImageRepository.getImageFromAssetFile(realView_.getContext(), "arrowfocus.png");
        /* 翻转180度 */
        Matrix matrix = new Matrix();
        matrix.postRotate(180);
        if (null != rightArrowNormal_) {
            arrowW = rightArrowNormal_.getWidth();
            arrowH = rightArrowNormal_.getHeight();
            leftArrowNormal_ = Bitmap.createBitmap(rightArrowNormal_, 0, 0, arrowW, arrowH, matrix, true);
            leftArrowFocus_ = Bitmap.createBitmap(rightArrowFocus_, 0, 0, arrowW, arrowH, matrix, true);
        }
    }

    public void releaseResource(Component component) {
        super.releaseResource(component);
        if (null != etNormalBack_)
            etNormalBack_.recycle();
        etNormalBack_ = null;
        if (null != etFocusBack_)
            etFocusBack_.recycle();
        etFocusBack_ = null;

        if (null != leftArrowNormal_)
            leftArrowNormal_.recycle();
        leftArrowNormal_ = null;
        if (null != leftArrowFocus_)
            leftArrowFocus_.recycle();
        leftArrowFocus_ = null;
        if (null != rightArrowNormal_)
            rightArrowNormal_.recycle();
        rightArrowNormal_ = null;
        if (null != rightArrowFocus_)
            rightArrowFocus_.recycle();
        rightArrowFocus_ = null;

        linkedUrl_ = null;
        if (null != cssStyle_)
            cssStyle_.releaseResource();
        cssStyle_ = null;
    }
}
